package com.hisoka.service;

import com.hisoka.domain.MailAuth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author Hinsteny
 * @Describtion
 * @date 2017/3/27
 * @copyright: 2016 All rights reserved.
 */
@Component
public class MailAuthService implements InitializingBean {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    RedisTemplate<String, MailAuth> redisTemplate;

    private static String MAILAUTH_KEY = "mail";

    public MailAuth getMailAuth(int shardingItem) {
//        MailAuth mailAuth = (MailAuth)this.redisTemplate.opsForHash().get(MAILAUTH_KEY, user.getUsername());
        logger.info("Get mailauth account by shardingItem: {}", shardingItem);
        //先获取到账号列表
        List<Object> auths = this.redisTemplate.opsForHash().values(MAILAUTH_KEY);
        return (null != auths && auths.size() > 0) ? filterMailAuthList(auths, shardingItem) : null;
    }

    /**
     * 可以自己定义缓存中的账号列表与es-job分片的关系, 这里简单的用取模方式映射
     * @param auths
     * @param shardingItem
     * @return
     */
    private MailAuth filterMailAuthList(List<Object> auths, int shardingItem) {
        int index = auths.size() % shardingItem;
        return (MailAuth) auths.get(index);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        MailAuth auth = new MailAuth();
        auth.setMailHost("smtp.163.com");
        auth.setMailAcount("hinsteny@163.com");
        auth.setMailPassword("kuqnvlbpeqpjgrok");
        this.redisTemplate.opsForHash().put(MAILAUTH_KEY, auth.getMailAcount(), auth);
        auth = new MailAuth();
        auth.setMailHost("smtp.qq.com");
        auth.setMailAcount("hinsteny@qq.com");
        auth.setMailPassword("lalalalalalalal");
        this.redisTemplate.opsForHash().put(MAILAUTH_KEY, auth.getMailAcount(), auth);
    }
}
